<?php
include('functions.inc.php');
set_time_limit(3550);
$link = db_connect();

if (isset($argc) && $argc > 2) {
	die("Usage: php $argv[0] [SubscriptionID]\nOptional SubscriptionID will load articles from this feed only.\n");
}
# Local authentication
if (!isset($argc) && (!isset($_GET['passphrase']) || $_GET['passphrase'] != $config['passphrase'])) {
	die("Authentication error.\n");
}

error_reporting(E_ALL ^ E_WARNING ^ E_NOTICE);

define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
define('MAGPIE_FETCH_TIME_OUT', 60);
require_once('magpierss/rss_fetch.inc');

include('create_tables.inc.php');

$subs_query = "SELECT id,url FROM subscriptions ORDER BY RAND()";
if (isset($argc) && $argc == 2) {
	$subs_query = "SELECT id,url FROM subscriptions WHERE id = " . mysql_real_escape_string($argv[1], $link);
}
else if (isset($_GET['sid'])) {
	$subs_query = "SELECT id,url FROM subscriptions WHERE id = " . mysql_real_escape_string($_GET['sid'], $link);
}
$result = mysql_query($subs_query, $link)
	or die("Can't load subscriptions: " . mysql_error() . "\n");

while ($subscription = mysql_fetch_array($result)) {
	$url = $subscription['url'];
	$subId = $subscription['id'];

	// Proxy RSS feed to clean it up first
	$url = $config['URI'].'/rssproxy.php?url='.urlencode($url).'&passphrase='.$config['passphrase'];

	$old_error_reporting = error_reporting(E_ERROR);
	$rss = fetch_rss($url);
	if ($rss === false) {
		error_reporting($old_error_reporting);
		glog("Error loading [$subId] $url");
		$query = sprintf("UPDATE subscriptions SET error = '%s' WHERE id = $subId", mysql_escape_string(magpie_error()));
		mysql_query($query, $link)
			or die("Can't update subscriptions.error: " . mysql_error() . "\n");
		continue;
	}
	error_reporting($old_error_reporting);

	if (count($rss->items) == 0) {
		glog("Error loading [$subId] $url - No items found in RSS feed.");
		mysql_query("UPDATE subscriptions SET error = 'GobbleRSS: No items found in RSS feed.' WHERE id = $subId", $link)
			or die("Can't update subscriptions.error: " . mysql_error() . "\n");
		continue;
	}

	if (!isset($_GET['sid'])) {
		glog("Loading [$subId] $url ... Found " . count($rss->items) . " items.");
	}
	mysql_query("UPDATE subscriptions SET last_updated = NOW(), error = 'OK: ".count($rss->items)."' WHERE id = $subId", $link)
		or die("Can't update subscriptions.last_updated & .error: " . mysql_error() . "\n");
	$numItems = 0;
	foreach($rss->items as $item) {
		unset($guid); unset($description);
		$numItems++;
		if (isset($item['pubDate'])) {
			$item['pubdate'] = $item['pubDate'];
		}
		if (isset($item['dc']['date'])) {
			$item['pubdate'] = ereg_replace('(....-..-..)T(..:..:..)([+-])(..):(..)', "\\1 \\2 \\3\\4\\5", $item['dc']['date']);
		}
		if (isset($item['published'])) {
			$item['pubdate'] = ereg_replace('(....-..-..)T(..:..:..)Z', "\\1 \\2 +0000", $item['published']);
		}
		if (isset($item['pubdate'])) {
			$pubDate = $item['pubdate'];
			$timestamp = strtotime($pubDate);
			$pubDate = date("Y-m-d H:i:s", $timestamp);
		} else {
			$pubDate = date("Y-m-d H:i:s", time());
		}

		$category = '';
		if (isset($item['category'])) {
			$category = $item['category'];
		}
		if (isset($item['guid'])) {
			$guid = $item['guid'];
		}
		$title = $item['title'];
		$alink = $item['link'];
		if (ereg('http://[^\?]*http://.*', $alink)) {
			$alink = ereg_replace('(http://[^\?]*)http://.*', "\\1", $alink);
		}
		if (!isset($guid)) {
			$guid = $alink;
		}
		$guid_prefix = '';
		if (ereg("(https?://www\\.)", $guid, $regs) || ereg("(https?://us\\.)", $guid, $regs) || ereg("(https?://)", $guid, $regs)) {
			$guid_prefix = $regs[1];
			$guid = str_replace($guid_prefix, '', $guid);
		}
		if (isset($item['description'])) {
			$description = $item['description'];
		}
		if (isset($item['atom_content'])) {
			$description = $item['atom_content'];
		}
		if (isset($item['content']['encoded'])) {
			$description = $item['content']['encoded'];
		}
		if (isset($item['summary'])) {
			$description = $item['summary'];
		}
		if (!isset($description)) {
			$description = $alink;
		}

		$insert_query = sprintf("INSERT INTO articles (subId, guid_prefix, guid, pubDate, title, link, description, category) VALUES ($subId, '%s', '%s', '%s', '%s', '%s', '%s', %s)",
			mysql_real_escape_string($guid_prefix, $link),
			mysql_real_escape_string($guid, $link),
			mysql_real_escape_string($pubDate, $link),
			mysql_real_escape_string($title, $link),
			mysql_real_escape_string($alink, $link),
			mysql_real_escape_string($description, $link),
			$category == '' ? "null" : "'" . mysql_real_escape_string($category, $link) . "'"
		);
		if (!mysql_query($insert_query, $link)) {
			if (mysql_errno() == 1062) {
				$insert_query = sprintf("UPDATE articles SET pubDate='%s', title='%s', link='%s', description='%s', category=%s WHERE guid='%s'", 
					mysql_real_escape_string($pubDate, $link),
					mysql_real_escape_string($title, $link),
					mysql_real_escape_string($alink, $link),
					mysql_real_escape_string($description, $link),
					$category == '' ? "null" : "'" . mysql_real_escape_string($category, $link) . "'",
					mysql_real_escape_string($guid_prefix, $link),
					mysql_real_escape_string($guid, $link)
				);
				mysql_query($insert_query, $link);
			}
		}
		if (mysql_errno() != 0 && mysql_errno() != 1062) {
			glog("Failed query: " . $insert_query . " - Error: " . mysql_error());
		}
	}
}

if (isset($_GET['sid'])) {
	$subs_query = "SELECT * FROM subscriptions WHERE id = " . mysql_real_escape_string($_GET['sid'], $link);
	$result = mysql_query($subs_query, $link)
		or die("Can't load subscriptions: " . mysql_error());
	$subscription = mysql_fetch_object($result);
	echo $subId.';'.getLastUpdatedHTML($subscription);
}

mysql_close($link);
?>
